package com.monolithiot.cdn.management.controller;

import com.monolithiot.cdn.management.common.context.Constants;
import com.monolithiot.cdn.management.common.entity.Project;
import com.monolithiot.cdn.management.common.entity.User;
import com.monolithiot.cdn.management.common.vo.BasicJsonResult;
import com.monolithiot.cdn.management.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * 2018/11/20 Create by 郭文梁
 * ProjectController
 * 项目数据访问控制器
 *
 * @author 郭文梁
 * @date 2018/11/20
 */
@RestController
@RequestMapping("/project")
public class ProjectController {
    private final ProjectService projectService;

    @Autowired
    public ProjectController(ProjectService projectService) {
        this.projectService = projectService;
    }

    /**
     * 创建项目
     *
     * @param project 项目（name,note,contextPath）
     * @param user    会话
     * @return BJR with project entity
     */
    @PostMapping("/_create")
    public BasicJsonResult<Project> create(Project project,
                                           @SessionAttribute(Constants.Key.USER_IN_SESSION_KEY) User user) {
        assert user != null;

        Project res = projectService.create(project, user);
        return BasicJsonResult.ok(res);
    }

    /**
     * 查看所有项目
     *
     * @return BJR with Project list
     */
    @GetMapping("/list")
    public BasicJsonResult<List<Project>> list() {
        List<Project> list = projectService.list();
        return BasicJsonResult.ok(list);
    }

    /**
     * 解压项目文件
     *
     * @param id 项目ID
     * @return BJR with Project Entity
     */
    @PostMapping("/{id}/_unzip")
    public BasicJsonResult<Project> unzip(@PathVariable("id") Integer id) {
        Project project = projectService.findById(id);
        if (project == null) {
            return BasicJsonResult.error(1, "项目不存在");
        }

        Project res;
        try {
            res = projectService.unzip(project);
        } catch (IOException e) {
            return BasicJsonResult.error(2, "文件不是Zip格式压缩文件");
        }
        return BasicJsonResult.ok(res);
    }
}
